<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api\developer;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketAddonVersions;
use addons\cloud_market\model\CloudMarketOrder;
use addons\cloud_market\model\CloudMarketSite;

class Order extends CloudMarketApiController
{
    protected $notApiCheck = ['*'];

    /**
     * @var CloudMarketOrder
     */
    protected $model = null;

    public $dev_id = 0;
    public $user_id = 0;

    public function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketOrder();
        $this->Site = new CloudMarketSite();
        $this->version_model = new CloudMarketAddonVersions();
        $user = $this->getUser();
        if (!$user['developer']) {
            showMessage("您没有权限", 'error', '', '-1');
        }
        $this->dev_id = $user['developer']['id'];
        $this->user_id = $user['id'];
    }

    /**
     * 【商城】获取列表
     */
    public function list()
    {
        // 获取当前用户有权限的订单
        $aids = (new CloudMarketAddon())->where(['user_id' => $this->user_id, 'dev_id' => $this->dev_id])->column('id');
        $mix['$where'] = [['aid', 'in', $aids]];
        $res = $this->model->getPageList($mix);
        $data = $res['data']->append(['addon', 'site', 'addonSku', 'user', 'agentUser']);
        return $this->success($res['count'], $data);
    }

    /**
     * 代付款
     * Create by :  刘泓宾<514660094@qq.com>
     */
    public function behalfPay()
    {
        $out_trade_no = input('out_trade_no', '');
        $order = $this->model->where(['out_trade_no' => $out_trade_no, 'status' => 0])->find();
        if ($order['type'] == 'buy_addon') {
            $res = $this->model->sendAddon($out_trade_no);
        } elseif ($order['type'] == 'buy_service') {
            $res = $this->model->sendService($out_trade_no);
        } elseif ($order['type'] == 'buy_token') {
            $res = $this->model->sendToken($out_trade_no);
        }
        if ($res) {
            $order->agent_id = $this->user_id;
            $order->save();
            return $this->success('代付款成功');
        } else {
            return $this->error($this->model->error, [$order, $res,$this->model->error]);
        }
    }

}
